package middleware

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
	"testPaper/common"
	"testPaper/model"
	"testPaper/response"
)

func WxInfoWare() gin.HandlerFunc {
	return func(c *gin.Context) {
		//DB := common.GetDB()
		//获取Authorization header
		tokenString := c.GetHeader("Authorization")

		if tokenString == "" || !strings.HasPrefix(tokenString, "eyJhbG") {
			response.Reponse(c, http.StatusOK, 401, nil, "token不正确")
			c.Abort()
			return
		}
		token, claims, err := common.ParseToken(tokenString)

		if err != nil || !token.Valid {
			response.Reponse(c, http.StatusOK, 401, nil, "token解析错误")
			c.Abort()
			return
		}

		//// 验证 claims 中的 userId
		//userId := claims.UserId
		//var wxUser model.WxUser
		//DB.First(&wxUser, userId)
		//
		//if wxUser.ID == 0 {
		//	response.Reponse(c, http.StatusOK, 401, nil, "用户不存在")
		//	return
		//}
		////用户信息存在 将 user 的信息写入上下文
		//c.Set("user", wxUser)
		c.Set("claims", claims)
		c.Next()
	}
}
func AppInfoWare() gin.HandlerFunc {
	return func(c *gin.Context) {
		DB := common.GetDB()
		//获取Authorization header
		tokenString := c.GetHeader("Authorization")

		if tokenString == "" || !strings.HasPrefix(tokenString, "eyJhbG") {
			response.Reponse(c, http.StatusOK, 401, nil, "token不正确")
			c.Abort()
			return
		}
		token, claims, err := common.ParseToken(tokenString)

		if err != nil || !token.Valid {
			response.Reponse(c, http.StatusOK, 401, nil, "token解析错误")
			c.Abort()
			return
		}

		//// 验证 claims 中的 userId
		userId := claims.UserId
		var wxUser model.WxUser
		DB.First(&wxUser, userId)

		if wxUser.ID == 0 {
			response.Reponse(c, http.StatusOK, 401, nil, "用户不存在")
			return
		}
		//用户信息存在 将 user 的信息写入上下文
		c.Set("user", wxUser)
		c.Next()
	}
}
